/**
 * 剑指 Offer 43. 1～n 整数中 1 出现的次数
 * https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/
 */

/**
 * @param {number} n
 * @return {number}
 */
function countDigitOne(n) {
  let count = 0;
  let rest = n;
  let digitIndex = 0;
  while (rest) {
    const mod = 10 ** digitIndex;
    const digit = rest % 10;
    rest = Math.floor(rest / 10);
    if (digit > 1) {
      count += mod;
    } else if (digit === 1) {
      count += ((n % mod) + 1);
    }
    count += (rest * mod);
    digitIndex += 1;
  }
  return count;
}

console.log(countDigitOne(12) === 5);
console.log(countDigitOne(13) === 6);
